import {ref} from 'vue'
import {useMenuStore} from "@/stores/menu.js";
import {ArrowDown} from "@element-plus/icons-vue";
//同步路由
import {useRoute, useRouter,onBeforeRouteUpdate} from "vue-router";
//设置缓存
import {setTabList,getTabList} from "@/composables/cookie.js";

export function useTabList(){
//设置宽度

    const menuStore = useMenuStore()
    const route = useRoute()
    const activeTab = ref(route.path)

    //当前选中的tab
    const tabList  = ref([
        {
            title: '仪表盘',
            path: '/admin/index'
        }
    ])


    //添加tab标签页
    function addTab  (tab){
        //校验标签是否不存在
        let isTabNotExisted = tabList.value.findIndex(item=> item.path === tab.path) === -1
        if(isTabNotExisted){
            tabList.value.push(tab)
        }
        //存储标签到缓存
        setTabList(tabList.value)
    }
    function initTabList(){
        //从缓存中获取导航栏信息
        let  tabs = getTabList()
        if(tabs){
            tabList.value = tabs
        }
    }
    // 初始化标签导航栏
    initTabList()


    // 在路由切换前被调用
    onBeforeRouteUpdate((to,form)=>{
        //设置被激活的标签
        activeTab.value=to.path
        // console.log({title:to.meta.title, path: to.path})
        addTab({title:to.meta.title, path: to.path})
    })

    //标签页切换
    const router = useRouter()
    const tabChange = (path)=>{
        console.log(path)
        activeTab.value=path
        router.push(path)
    }


    //删除标签页
    const removeTab= (path)=>{
        let tabs = tabList.value
        //当前选中的tab标签
        let actTab = activeTab.value

        // 如果要删除的是当前被选中的标签页，则需要判断其被删除后，需要激活哪个 tab 标签页
        if(actTab === path){
            tabs.forEach((tab,index)=>{
                //获取选中的tab
                if(tab.path === path){
                    // 拿到被选中的标签页下标，如果它后面还有标签页，则取下一个标签页，否则取上一个
                    let nextTab = tabs[index+1] || tabs[index-1]
                    if(nextTab){
                        actTab = nextTab.path
                    }
                }
            })
        }

        //需被激活的标签页
        activeTab.value = actTab
        //过滤被删除的标签页
        tabList.value = tabList.value.filter((tab)=> tab.path !==path)

        setTabList(tabList.value)
        tabChange(activeTab.value)

    }

//处理关闭标签菜单事件
    const handleCloseTab = (command)=>{
        console.log(command)
        //首页地址
        let indexPath= '/admin/index'
        //处理关闭其他
        if(command==='closeOthers'){
            tabList.value = tabList.value.filter((tab)=> tab.path=== indexPath || tab.path === activeTab.value)
        }else if(command==='closeAll'){
            activeTab.value = indexPath
            tabList.value = tabList.value.filter((tab)=> tab.path === indexPath)
            tabChange(activeTab.value)
        }
        //加入缓存
        setTabList(tabList.value)
    }


    return{
        menuStore,
        activeTab,
        tabList,
        tabChange,
        removeTab,
        handleCloseTab
    }

}











